package cn.wangyinpeng.dao.jdbc.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * jdbc工具类
 * @author <a href="mailto:wypjs1@gmail.com">velin</a>
 *
 */
public class JDBCUtils {
	private static Properties databaseProperties = new Properties();
	private static JDBCUtils utils = new JDBCUtils();
	private JDBCUtils(){}
	static {
		try {
			//加载配置文件
			databaseProperties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("database.properties"));
			
		} catch (IOException e1) {
			throw new ExceptionInInitializerError("database.properties not found");
		}
		try {
			//加载驱动
			Class.forName(databaseProperties.getProperty("driver"));
		} catch (ClassNotFoundException e) {
			throw new  ExceptionInInitializerError("加载"+databaseProperties.getProperty("driver")+"失败");
		}
	}
	
	
	/**
	 * 得到实例
	 * @return
	 */
	public static JDBCUtils newInstance()
	{
		return utils;
	}
	/**
	 * 获得配置文件
	 * @return
	 */
	public Properties getProperties()
	{
		return databaseProperties;
	}
	
	/**
	 * 获取连接
	 * @return
	 */
	public Connection getConnection()
	{
		Connection conn =null;
		try {
			 conn = DriverManager.getConnection(databaseProperties.getProperty("url"),
					databaseProperties.getProperty("username"),
					databaseProperties.getProperty("password"));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new ExceptionInInitializerError("连接数据库失败");
		}
		
		return conn;
	}

	public void free(ResultSet rs, Statement st, Connection conn) throws SQLException
	{
		
			try {
				if (rs != null)
				rs.close();
			} 
			finally
			{
				if (st != null)
					try{
						st.close();
					}
					finally
					{
						if (conn!=null)
							conn.close();
					}
				
			}
	}
}
